using System;
using System.Globalization;
using System.Windows;
using WPFTemplateLib.WpfConverters.Core;

/*
 * 源码已托管：https://gitee.com/dlgcy/WPFTemplateLib
 * 版本：2024年10月11日
 */
namespace WPFTemplateLib.WpfConverters
{
	/// <summary>
	/// [转换器] bool 转 Grid 行/列 中的 高/宽（<see cref="GridLength"/>）[属性版] <para/>
	/// [说明] 绑定值（支持 bool、string、数值 类型）（或翻转后）为 false, 则 高/宽 转为 [FalseValue] 指定的值。<para/>
	/// 绑定值（或翻转后）为 true, 则 高/宽 转为 [TrueValue] 指定的值。
	/// </summary>
	/// <example>
	///	<code>
	///	Converter={wpfConverters:BoolToGridLengthConverterV2 TrueValue='*', FalseValue=30}
	/// </code>
	/// </example>
	public class BoolToGridLengthConverterV2 : ValueConverterBase
	{
		/// <summary>
		/// 绑定值（或翻转后）为 false 时对应需转换到的值（支持 n*、Auto、具体值）
		/// </summary>
		public string TrueValue { get; set; }

		/// <summary>
		/// 绑定值（或翻转后）为 false 时对应需转换到的值
		/// </summary>
		public double FalseValue { get; set; }

		/// <summary>
		/// 绑定的 bool 值是否翻转后再计算
		/// </summary>
		public bool IsReversed { get; set; }

		/// <inheritdoc />
		public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			GridLength gridLength = GridLength.Auto;
			try
			{
				bool boolValue = false;
				if(value is bool b)
				{
					boolValue = b;
				}
				else if(value is string s)
				{
					boolValue = !string.IsNullOrWhiteSpace(s);
				}
				else
				{
					bool res = double.TryParse(value + "", out double d);
					if(res)
					{
						boolValue = d > 0;
					}
				}

				if (IsReversed) boolValue = !boolValue;

				if (boolValue)
				{
					string para = TrueValue + "";
					if (!string.IsNullOrWhiteSpace(para))
					{
						if (para == "Auto" || para == "auto")
						{
							//Ignore
						}
						else if (para.Contains("*"))
						{
							int index = para.IndexOf("*", StringComparison.Ordinal);
							string numStr = para.Remove(index).Trim();
							if (string.IsNullOrWhiteSpace(numStr))
							{
								numStr = "1";
							}

							double.TryParse(numStr, out double num);
							if (num > 0)
							{
								gridLength = new GridLength(num, GridUnitType.Star);
							}
							else
							{
								gridLength = new GridLength(0);
							}
						}
						else
						{
							double.TryParse(para.Trim(), out double num);
							if (num > 0)
							{
								gridLength = new GridLength(num, GridUnitType.Pixel);
							}
							else
							{
								gridLength = new GridLength(0);
							}
						}
					}
				}
				else
				{
					gridLength = new GridLength(FalseValue);
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex);
			}

			return gridLength;
		}

		/// <inheritdoc />
		public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			throw new NotImplementedException();
		}
	}
}
